package dmsxl.erchashu;

import java.util.*;

/**
 * Author: Zhang Dongwei
 * Date: 2023/5/5 16:44
 * 二叉树的层序遍历
 */
public class ecs5_199 {

    public static void main(String[] args) {
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(5);
        TreeNode node5 = new TreeNode(4);
        node1.left = node2;
        node1.right = node3;
        node2.right = node4;
        node3.right = node5;
        List<Integer> list = rightSideView(node1);
        System.out.println(list);
    }


    public static List<Integer> rightSideView(TreeNode root) {
        ArrayList<Integer> res = new ArrayList<>();
        LinkedList<TreeNode> que = new LinkedList<>();
        if (root == null) return res;
        que.offer(root);
        while (!que.isEmpty()){
            int size = que.size();
            for (int i = 0; i < size; i++){
                TreeNode poll = que.poll();
                if (poll.left != null) que.offer(poll.left);
                if (poll.right != null) que.offer(poll.right);
                if (i == size - 1) res.add(poll.val);
            }
        }
        return res;
    }
}